// components/tabs/index.js
const computedBehavior = require('miniprogram-computed');
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [computedBehavior],
  watch: {
    index(cur) {
      // console.log('change',cur);
      // console.log(this.data.tabs);
      this.check_scroll_left(`option${cur}`);
    }
  },
  ready() {
    setTimeout(() => {
      this.check_scroll_left(`option0`);
    }, 600)
  },
  properties: {
    tabs: {
      type: Array,
      value: []
    },
    active: {
      type: String,
      value: ''
    },
    index: {
      type: Number,
      value: 0
    },
    lineWidth: {
      type: Number,
      value: 32
    },
    lineHeight: {
      type: Number,
      value: 6
    },
    borderRadius: {
      type: Number,
      value: 3
    },
    lineColor: {
      type: String,
      value: '#FF5D62'
    },
    activeStyle: {
      type: String,
      value: ''
    },
    customStyle: {
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    toView: '',
    left: 0, //滚动条在什么位置
    load: 0, //第一次进入
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //前往选择元素
    to_view_handle(e) {
      // console.log(e.currentTarget.dataset.id);
      const {
        id,
        active,
        index
      } = e.currentTarget.dataset;
      // console.log(id)
      // console.log(e.currentTarget.dataset)
      this.check_scroll_left(id);
      this.setData({
        toView: id,
      })
      this.triggerEvent("onChange", {
        active,
        index,
      })
    },
    //滚动条位置计算
    check_scroll_left(id) {
      wx.nextTick(() => {
        var that = this;
        let left;
        const query = this.createSelectorQuery()
        query.selectAll(`#${id}`).boundingClientRect()
        query.exec(function (res) {
          const width = res[0][0].width;
          const offsetLeft = res[0][0].left;
          left = offsetLeft + (width - that.data.lineWidth) / 2;
          that.setData({
            left,
            load: that.data.load + 1
          })
        })
      })

    }
  }
})